import React, { PureComponent } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Card, message, Button, Modal } from 'antd';
import { StandardTable, SearchForm } from '@joy/joy-pro';
import { to } from '@/utils/smallTool';
import { connect } from 'dva';
import configData from './config-data.js';
import FormModal from './form-modal';
import { updateCityBusiness, saveCityBusiness, deleteCityBusiness } from '@/services/city';
import geo from '@/utils/city';

const pageInfo = { showSizeChanger: true, showQuickJumper: true, defaultPageSize: 10 };
const drawerWidth = '50%';
@connect(({ global, loading, business, authority, allcity }) => ({
  tableData: business.tableData,
  IssueChannelList: business.IssueChannelList,
  SalespersonList: business.SalespersonList,
  ManufactureList: business.ManufactureList,
  searchForm: business.searchForm,
  permissionsList: authority.permissionsList,
  tableLoading: loading.effects['business/getCityBusiness'],
  watermarkConfig: global.watermarkConfig,
  cityList: allcity.cityList
}))
class ReportFund extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      params: {},
      pageRequest: {
        pageNum: 1,
        pageSize: 10,
      },
      drawerStatus: {
        visible: false
      },
      resultDate: [],
      loading: true,
      activeRecord: {},
      inputConfig: configData.getFundSearchInputConfig(props.cityList)
    };
    this.$drawerForm = React.createRef();
    const { pageRequest, params } = this.state;
    this.getSelectList();
    this.getQueryList(params, pageRequest);
  }
  /**
   * @description 条件筛选 [搜索]
   * @author zhe
   * @date 2020-04-13
   * @param {*} formData
   * @param {*} reaclData
   * @param {*} isClear
   * @memberof
   */
  actionSearch = (formData, reaclData, isClear) => {
    const params = formData;
    const pageRequest = { pageNum: 1, pageSize: 10 };
    this.setState({
      params: params,
    });
    this.getQueryList(params, pageRequest);
  };

  /**
   * @description 请求列表数据
   * @author zhe
   * @date 2020-04-13
   * @param {*} params
   * @param {*} pageRequest
   * @memberof
   */
  getQueryList = (params, pageRequest) => {
    const type = 'business/getCityBusiness';
    const param = Object.assign(pageRequest, params, { type: '2' });
    const { dispatch } = this.props;
    dispatch({
      type,
      payload: param,
    });
  };
  handleSaveCityBusiness(type) {
    const requestConfig = {
      'add': saveCityBusiness,
      'update': updateCityBusiness
    }
    return async function (validateRes) {
      let postRes = false;
      const dataObj = await requestConfig[type](validateRes);
      if (dataObj && dataObj.code === '000000') {
        message.success('操作成功');
        postRes = true;
      } else {
        message.error('操作失败');
      }
      return postRes;
    }
  }

  /**
   * @description 请求事件类型下拉列表数据
   * @author zhe
   * @date 2020-04-14
   * @memberof
   */
  getSelectList = async () => {
    const type = 'allcity/getCityByPage';
    const { dispatch } = this.props;
    const cityList = await dispatch({
      type
    });
    this.setState({
      inputConfig: configData.getFundSearchInputConfig(cityList)
    })
  };
  /**
   * @description 删除
   * @author zhe
   * @date 2020-04-13
   * @param {*} params
   * @param {*} pageRequest
   * @memberof
   */
  deleteData = async activeRecord => {
    const dataObj = await deleteCityBusiness({ cityCode: activeRecord.cityCode, type: 2 });
    if (dataObj && dataObj.code === '000000') {
      if (dataObj.data !== null) {
        message.success('操作成功');
      } else {
        message.error('操作失败');
      }
    }
  };
  /**
   * @description table操作触发改变事件
   * @author songs
   * @date 2019-07-12
   * @param {*} pagination
   * @param {*} filtersArg
   * @param {*} sorter
   * @memberof managementUser
   */
  handleStandardTableChange = (pagination, filtersArg, sorter, actionType) => {
    const { pageSize, current } = pagination;
    const pageNum = current;
    const pageRequest = { pageSize, pageNum };
    this.getQueryList(filtersArg, pageRequest);
  };
  handleRefreshList = () => {
    const { params } = this.state;
    const { tableData } = this.props;
    const { pagination = {} } = tableData;
    const { pageNum, pageSize } = pagination;
    const pageRequest = { pageNum: pageNum, pageSize: pageSize };
    this.getQueryList(params, pageRequest);
  }
  handleTransData(data, cityList) {
    data.type = 2;
    if (!data.cityCode) {
      data.cityCode = data.cityName;
      data.cityName = geo.getCityNameByCode(cityList, data.cityCode);
    }
    return data;
  }
  /**
   * @description 抽屉表单提交事件
   */
  onDrawerOk = async () => {
    const { validateFields } = this.$drawerForm.current.props.form;
    let [validateError, validateRes] = await to(validateFields());
    if (validateError) return false;
    validateRes = this.handleTransData(validateRes);
    let postRes = await this.handleSaveCityBusiness(this.state.drawerStatus.type)(validateRes);
    if (postRes) {
      this.handleRefreshList();
      this.changeDrawerStatus(false);
    }
    return true;
  };

  /**
   * @description 切换抽屉状态
   * @author songs
   * @param {Boolean} visible
   * @param {String} type
   * @param {Object} activeRecord
   */
  changeDrawerStatus = (visible, type, activeRecord = {}, event) => {
    this.setState(oldState => ({
      ...oldState,
      drawerStatus: { visible, type },
      activeRecord,
    }));
  };

  /**
   * @description 解析抽屉内表单配置信息
   * @param {*} type
   * @returns
   */
  ravDrawerConfig = cityList => {
    const { activeRecord } = this.state;
    return configData.getEditInputConfig({ ...activeRecord, cityList });
  };
  handleDelete = record => {
    const _this = this;
    Modal.confirm({
      content: '确认删除该数据？',
      onOk: () => {
        this.deleteData(record).then(() => {
          this.handleRefreshList();
        });
      }
    })
  };
  // 代缴订单列表
  tableCol = () => {
    const OptionNode = ({ record }) => (
      <div>
        <Button
          type="link"
          style={{ display: 'block' }}
          onClick={() => {
            this.changeDrawerStatus(true, 'update', record);
          }}
        >
          修改
        </Button>
        <Button
          type="link"
          style={{ display: 'block' }}
          onClick={() => {
            this.handleDelete(record);
          }}
        >
          删除
        </Button>
      </div>
    );
    return configData.getTableConfig(OptionNode);
  };

  render() {
    const { tableCol, ravDrawerConfig, onDrawerOk, changeDrawerStatus, $drawerForm } = this;
    const { drawerStatus, resultDate, inputConfig } = this.state;
    const { tableLoading, watermarkConfig, tableData, cityList } = this.props;
    const { list = [], pagination = {} } = tableData;
    const editInputConfig = ravDrawerConfig(cityList);
    return (
      <div>
        <PageHeaderWrapper title="" className="hasContent">
          <div style={{ background: '#fff', padding: '20px 0px 0px 24px', marginBottom: '10px' }}>
            <SearchForm
              defaultInput={inputConfig.slice(0, 3)}
              moreInput={inputConfig.slice(3)}
              gutter={{ md: 10 }}
              useCol={{ sm: 24, md: 12, xl: 8, xxl: 8 }}
              onSearch={this.actionSearch}
            ></SearchForm>
          </div>
          <Card bordered={false}>
            <div style={{ marginBottom: '10px', overflow: 'hidden' }}>
              <Button style={{ float: 'right', marginLeft: '20px' }} onClick={() => this.changeDrawerStatus(true, 'add')} type="primary">
                新增
              </Button>
            </div>
            <StandardTable
              isWatermark
              watermark={{ ...watermarkConfig }}
              dataSource={list}
              pagination={{ ...pagination, ...pageInfo }}
              columns={tableCol()}
              loading={tableLoading}
              rowKey={(record, index) => index}
              onChange={($pagination, filtersArg, sorter) => {
                this.handleStandardTableChange($pagination, this.state.params, sorter, 'business/getCityBusiness');
              }}
            ></StandardTable>
          </Card>
        </PageHeaderWrapper>
        <Modal
          title='城市业务'
          width={drawerWidth}
          destroyOnClose
          closable={false}
          onCancel={e => {
            changeDrawerStatus(false);
          }}
          onOk={e => {
            onDrawerOk();
          }}
          visible={drawerStatus.visible}
        >
          <FormModal defaultData={editInputConfig} wrappedComponentRef={$drawerForm} />
        </Modal>
      </div>
    );
  }
}

export default ReportFund;
